import { getUserInfoApi, loginApi, getUserDetailByIdApi } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    setToken(data)
    state.token = data
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await loginApi(data)
    console.log('vuex', res)
    // store.commit('setToken', res.data.data)
    // 响应拦截器做过解构, 无需再取子属性
    store.commit('setToken', res)

    // 为了之后发请求可以主动校验是否已经失效, 记录当前的登录时间
    localStorage.setItem('loginTime', Date.now())

    // loginApi(data).then(res => {
    //   console.log('vuex', res)
    //   store.commit('setToken', res.data.data)
    // })
  },
  async getUserInfo(store) {
    const res = await getUserInfoApi()
    // 默认当前账号基本信息数据不足
    // 需要另外一个员工数据接口进行补充
    const detail = await getUserDetailByIdApi(res.userId)

    store.commit('setUserInfo', {
      ...res,
      ...detail
    })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
